﻿using System;
using System.Diagnostics;
using System.IO;
using System.Threading.Tasks;
using API;
using CoreGraphics;
using Foundation;
using Masonry;
using MyExtensions;
using UIKit;

namespace mb
{
    public partial class App
    {
        public static UIKit.UIColor MainColor = UIKit.UIColor.FromRGB(251, 114, 153);
    }
}

namespace mb.iOS
{
    [Register("AppDelegate")]
    public class AppDelegate : UIApplicationDelegate
    {
        public override UIWindow Window { get; set; }
        static public AppDelegate Instance { get; set; }
        public VCMyNavigation NavController;

        public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions)
        {
            Instance = this;
            NavController = new VCMyNavigation(new StartViewController());
            Window = new UIWindow(UIScreen.MainScreen.Bounds)
            {
                BackgroundColor = App.MainColor,
                RootViewController = NavController,
            };
            Window.MakeKeyAndVisible();

            SetupGlobalExceptionCatcher();
            return true;
        }

        void SetupGlobalExceptionCatcher()
        {

            AppDomain.CurrentDomain.UnhandledException += (sender, args) => InvokeOnMainThread(new Action(() =>
            {
                var exception = ((Exception) args.ExceptionObject);
                string message = "";
                if (exception.InnerException != null)
                    message = exception.Message + Environment.NewLine + exception.InnerException.Message;
                else
                    message = exception.Message;

                var logger = ServiceLocator.Instance.Get<ILog>();
                logger.Log("** GeneralErrorMessage", message);
            }));

            TaskScheduler.UnobservedTaskException += (sender, e) =>
            {
                var logger = ServiceLocator.Instance.Get<ILog>();
                logger.Log("** UnobservedTaskException", e.Exception);
            };

        }

        public override void OnResignActivation(UIApplication application) { }

        public override void DidEnterBackground(UIApplication application) { }

        public override void WillEnterForeground(UIApplication application) { }

        public override void OnActivated(UIApplication application) { }

        public override void WillTerminate(UIApplication application) { }
    }
}